/*
 * Copyright 2013-2018 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.AI.AIDemo.Demos.Web.Config;

import cn.hutool.core.util.IdUtil;
import com.aliyun.oss.OSS;

import com.aliyun.oss.OSSClientBuilder;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.ApplicationRunner;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.PreDestroy;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * OSS common config.
 *
 * @author <a href="mailto:chenxilzx1@gmail.com">theonefx</a>
 */
@Data
@Configuration
@Slf4j
public class OssConfig {

	/**
	 * Bucket Name of OSS Example.
	 */
	public static final String BUCKET_NAME = "xgd-lokli-bucket";

	@Value("${alibaba.cloud.oss.endpoint}")
	private String endpoint;

	@Value("${alibaba.cloud.access-key}")
	private String accessKeyId;

	@Value("${alibaba.cloud.secret-key}")
	private String accessKeySecret;

	@Autowired
	private OSS ossClient;

	/**
	 * 与OSSClientBuilder.build()方法创建OSSClient实例。
	 */
	@Bean
	public OSS ossClient() {
		this.ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
		return this.ossClient;
	}

	/**
	 * You can use these code to check or create oss bucket. Or manage buckets in
	 * <a href="https://oss.console.aliyun.com/bucket">oss console</a>.
	 */
	@Bean
	public ApplicationRunner ossBucketInitRunner() {
		return args -> {
			try {
				if (!ossClient.doesBucketExist(BUCKET_NAME)) {
					ossClient.createBucket(BUCKET_NAME);
					log.info("Successfully created bucket: {}", BUCKET_NAME);
				} else {
					log.info("桶名已存在: {}", BUCKET_NAME);
				}
			} catch (Exception e) {
				log.error("Failed to create or check bucket: {}", BUCKET_NAME, e);
				throw new RuntimeException("Failed to initialize OSS bucket", e);
			}
		};
	}

	@PreDestroy
	public void shutdownOssClient() {
		if (ossClient != null) {
			ossClient.shutdown();
			log.info("OSS client has been shut down.");
		}
	}

	public String putObject(MultipartFile file, String fileType) throws IOException {
		OSS ossClient = ossClient();

		// 获取当前日期和时间
		LocalDateTime now = LocalDateTime.now();
		// 创建一个日期时间格式器，用于格式化为"yyyyMMdd"
		DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd");
		// 格式化当前日期和时间
		String time = now.format(formatter);

		// hutool获取uuid作为文件名
		String simpleUUID = IdUtil.simpleUUID();
		// 获取file 文件后缀
		String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".") + 1);
		// 上传路径+文件名
		String objectName = time+"/"+fileType+"/"+simpleUUID+"."+suffix;
		// 获取上传文件的输入流
		InputStream inputStream = file.getInputStream();
		// 调用OSS SDK的提交文件
		ossClient.putObject(BUCKET_NAME, objectName, inputStream);
		// 断开连接
		ossClient.shutdown();
		return time+"/"+fileType+"/"+simpleUUID+"."+suffix;
	}

	public ByteArrayOutputStream getObject(String objectName) throws IOException {
		//获取链接
		OSS ossClient = ossClient();
		// 获取文件输入流
		InputStream inputStream = ossClient.getObject(BUCKET_NAME, objectName).getObjectContent();

		//输出流
		ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
		// 1.9+ 的正确写法
		//byte[] buffer = inputStream.readAllBytes();
		//1.8的写法 while循环获取
		byte[] buffer = new byte[1024];
		int bytesRead;
		while ((bytesRead = inputStream.read(buffer)) != -1) {
			outputStream.write(buffer, 0, bytesRead);
		}
		// 断开连接
		ossClient.shutdown();


		return outputStream;
	}
}
